package svgedit.gui.actions;


import java.awt.event.ActionEvent;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;
import javax.swing.AbstractAction;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

import svgedit.gui.Frame;
import svgedit.gui.SVGFileFilter;
import svgedit.gui.SVGZFileFilter;


/** Shows a file dialog for the user to select a new file to write the document
 *  to, then saves it at that location.
 */
@SuppressWarnings("serial")
public class SaveDocumentAsAction extends AbstractAction {

    private Frame frame;
    /** Create this action for the given frame */
    public SaveDocumentAsAction(Frame frame) {
        super("Save As...");
        this.frame = frame;
    }

    /**
     *   When invoke this action to save file as another format
     *   
     *   @param arg0 to monitor the action event
     * */
    public void actionPerformed(ActionEvent arg0) {
        File file = frame.getDocument().getFile();
        JFileChooser dialog;
        if (file != null)
            dialog = new JFileChooser(file);
        else
            dialog = new JFileChooser(frame.getPreferences().getDefaultPath());
        // Add the file filter
        dialog.addChoosableFileFilter(new SVGFileFilter());
        dialog.addChoosableFileFilter(new SVGZFileFilter());
        dialog.showSaveDialog(null);

        file = dialog.getSelectedFile();
        if (file != null) {
            if (file.exists()) {
                if (JOptionPane.showConfirmDialog(frame.getRootPane(), String.format("Do you want to replace the existing file named %s?", file.getName()), "Overwrite existing file?", JOptionPane.OK_CANCEL_OPTION) == JOptionPane.CANCEL_OPTION)
                    return;
            }
            frame.getPreferences().setDefaultPath(file.getPath());
            // If save file is ended with svg then save the file as usual
            if(dialog.getFileFilter().getDescription().equalsIgnoreCase("svg files"))
                frame.saveFile(file);
           
            else if (dialog.getFileFilter().getDescription().equals("SVGZ Files")){
            	try {
					SaveAsSVGZ(file);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
            }
        }
    }
      
    /**
     *  Save file as svgz file
     *      compress the svg file
     *      
     * @param file to get the written file 
     * @throws IOException when read and writer fails ,throw the exception
     * */
    public void SaveAsSVGZ(File file) throws IOException{
    	//create a temp file to store the contect to be saved
    	File tmpFile = new File(file.getName()+".svg");
    	// Write svg file into a temp file 
    	frame.saveFile(tmpFile);
    	//read the temp file 
    	BufferedReader reader = new BufferedReader(new FileReader(tmpFile));
    	String newfile = file.toString();
        if(!file.toString().endsWith(".svgz")){
    		  newfile = file.toString()+".svgz";
    	}
        // gzip the temp file and compress it into the target file
    	BufferedOutputStream writer = new BufferedOutputStream(new GZIPOutputStream(new FileOutputStream(newfile)));
    	int readbyte;
    	while((readbyte = reader.read())!= -1){
    		writer.write(readbyte);
    	}
    	reader.close();
    	writer.close();
    	//delete temp file
    	tmpFile.delete();
    }

}
